package likes

import (
	"context"
	"github.com/gin-gonic/gin"
	"net/http"
	"pingpong/redis"
	"strconv"
)

// LikeArticle 处理点赞文章的请求
func LikeArticle(c *gin.Context) {
	articleID := c.Param("id")
	likeKey := "article:" + articleID + ":likes"

	// 使用 context.Background() 创建一个空的上下文，如果你有特定的上下文可以传递
	ctx := context.Background()
	// 调用 Incr 方法，并传递上下文和键名
	if err := redis.RedisClient.Incr(ctx, likeKey).Err(); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"message": "fail set"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "like set successful"})
}

// GetArticleLikes 根据文章ID获取点赞数
func GetArticleLikes(c *gin.Context) {
	articleID := c.Param("id")
	likeKey := "article:" + articleID + ":likes"

	ctx := context.Background()

	// 使用 Redis 获取点赞数
	result, err := redis.RedisClient.Get(ctx, likeKey).Result()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"message": "error getting likes"})
		return
	}

	// 将结果转换为整数
	likes, err := strconv.Atoi(result)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"message": "error converting likes to int"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "likes retrieved successfully", "likes": likes})
}
